// 试题上传与管理模块
const db = wx.cloud.database();
const questionCollection = db.collection('questions');
const _ = db.command;

/**
 * 创建单个试题
 * @param {Object} question 试题数据
 * @returns {Promise} 创建结果
 */
async function createQuestion(question) {
  try {
    // 添加创建时间和更新时间
    question.createTime = db.serverDate();
    question.updateTime = db.serverDate();
    
    // 获取当前用户ID作为创建者
    const userInfo = await wx.cloud.callFunction({
      name: 'getUser',
      data: {}
    });
    question.creator = userInfo.result.openid;
    
    // 插入数据库
    const result = await questionCollection.add({
      data: question
    });
    
    return {
      success: true,
      questionId: result._id,
      message: '创建试题成功'
    };
  } catch (error) {
    console.error('创建试题失败', error);
    return {
      success: false,
      message: '创建试题失败: ' + error.message
    };
  }
}

/**
 * 批量导入试题（Excel）
 * @param {String} fileID 上传的Excel文件ID
 * @returns {Promise} 导入结果
 */
async function importQuestionsFromExcel(fileID) {
  try {
    // 调用云函数解析Excel文件
    const result = await wx.cloud.callFunction({
      name: 'question-import',
      data: {
        fileID
      }
    });
    
    const { success, total, successCount, failCount, failList } = result.result;
    
    return {
      success,
      total,
      successCount,
      failCount,
      failList,
      message: `导入完成，成功${successCount}题，失败${failCount}题`
    };
  } catch (error) {
    console.error('导入试题失败', error);
    return {
      success: false,
      message: '导入试题失败: ' + error.message
    };
  }
}

/**
 * OCR识别试题
 * @param {String} imagePath 图片临时路径
 * @returns {Promise} 识别结果
 */
async function recognizeQuestionByOCR(imagePath) {
  try {
    // 上传图片到云存储
    const fileRes = await wx.cloud.uploadFile({
      cloudPath: `ocr/${Date.now()}-${Math.random().toString(36).substr(2)}.png`,
      filePath: imagePath
    });
    
    // 调用OCR云函数
    const result = await wx.cloud.callFunction({
      name: 'ocr-recognize',
      data: {
        fileID: fileRes.fileID
      }
    });
    
    // 删除临时图片
    await wx.cloud.deleteFile({
      fileList: [fileRes.fileID]
    });
    
    return {
      success: true,
      ...result.result
    };
  } catch (error) {
    console.error('OCR识别失败', error);
    return {
      success: false,
      message: 'OCR识别失败: ' + error.message
    };
  }
}

/**
 * 查询试题列表
 * @param {Object} params 查询参数
 * @returns {Promise} 查询结果
 */
async function getQuestionList(params = {}) {
  try {
    const { subject, type, knowledge, difficulty, keyword, page = 1, size = 20 } = params;
    
    let query = questionCollection;
    
    // 构建查询条件
    if (subject) {
      query = query.where({
        subject: subject
      });
    }
    
    if (type) {
      query = query.where({
        type: type
      });
    }
    
    if (knowledge && knowledge.length > 0) {
      query = query.where({
        knowledge: _.in(knowledge)
      });
    }
    
    if (difficulty) {
      query = query.where({
        difficulty: difficulty
      });
    }
    
    if (keyword) {
      query = query.where({
        'content.stem': db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      });
    }
    
    // 获取总数
    const countResult = await query.count();
    const total = countResult.total;
    
    // 分页查询
    const result = await query
      .orderBy('createTime', 'desc')
      .skip((page - 1) * size)
      .limit(size)
      .get();
    
    return {
      success: true,
      questions: result.data,
      total,
      page,
      size
    };
  } catch (error) {
    console.error('查询试题失败', error);
    return {
      success: false,
      message: '查询试题失败: ' + error.message
    };
  }
}

/**
 * 更新试题
 * @param {String} questionId 试题ID
 * @param {Object} data 更新数据
 * @returns {Promise} 更新结果
 */
async function updateQuestion(questionId, data) {
  try {
    // 添加更新时间
    data.updateTime = db.serverDate();
    
    // 更新数据库
    await questionCollection.doc(questionId).update({
      data
    });
    
    return {
      success: true,
      message: '更新试题成功'
    };
  } catch (error) {
    console.error('更新试题失败', error);
    return {
      success: false,
      message: '更新试题失败: ' + error.message
    };
  }
}

/**
 * 删除试题
 * @param {String} questionId 试题ID
 * @returns {Promise} 删除结果
 */
async function deleteQuestion(questionId) {
  try {
    // 检查试题是否被试卷引用
    const checkResult = await wx.cloud.callFunction({
      name: 'checkQuestionUsage',
      data: {
        questionId
      }
    });
    
    if (checkResult.result.isUsed) {
      return {
        success: false,
        message: '该试题已被试卷引用，无法删除'
      };
    }
    
    // 删除试题
    await questionCollection.doc(questionId).remove();
    
    return {
      success: true,
      message: '删除试题成功'
    };
  } catch (error) {
    console.error('删除试题失败', error);
    return {
      success: false,
      message: '删除试题失败: ' + error.message
    };
  }
}

module.exports = {
  createQuestion,
  importQuestionsFromExcel,
  recognizeQuestionByOCR,
  getQuestionList,
  updateQuestion,
  deleteQuestion
}; 